package org.jiajie.coffeecodes.advice;

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

import java.lang.reflect.Method;
import java.math.BigDecimal;

/**
 * TimeLoggingAop 实现了前置增强，后置增强，异常环绕增强
 *
 * @author jie
 */
public class TimeLoggingAop implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {

    private long startTime = 0;

    @Override
    public void before(Method method, Object[] objects, Object o) throws Throwable {
        startTime = System.nanoTime();
    }

    @Override
    public void afterReturning(Object returnValue, Method method, Object[] objects, Object target) throws Throwable {
        long spentTime = System.nanoTime() - startTime;
        String clazzName = target.getClass().getCanonicalName();
        String methodName = method.getName();
        System.out.println("执行" + clazzName + "#" + methodName + "消耗" + new BigDecimal(spentTime).divide(new BigDecimal(1000000)) + "毫秒");
    }

    // method参数:将来调用的方法
    // args参数:将来调用方法时传的参数
    // target参数:目标对象
    // e参数:将来调用方法所抛出的异常（要么只有这一个参数，要么这四个参数都要有）
    public void afterThrowing(Method method, Object[] args, Object target, Exception ex) {
        System.out.println("执行" + method.getName() + "出现异常，" + "异常信息为：" + ex.getMessage());
    }

}
